package InterviewsExposed;

public class HeadTailSingleLinkedList {
	
	ListElement head, tail;
	
	public HeadTailSingleLinkedList(){
		
		head = null;
		tail = null;
	}
	
	public void insert(Object data){
		
		ListElement temp = new ListElement(data);
		if (head == null){
			head = temp;
			tail = head;
		}
		else{
			tail.next = temp;
			tail = temp;
		}
	}
	
	public ListElement getHead(){
		return this.head;
	}
	
	public ListElement getTail(){
		return this.tail;
	}
	
	public boolean remove(ListElement removeMe){
		
		if (this.head == null){
			return false;
		}
		else
		if (removeMe.getData() == head.getData()){
			head = head.next;
			return true;
		}
		else{
			ListElement run = this.head;
			while (run.next != null){
				
				if(removeMe.getData() == run.next.getData()){
					if(run.next.getData() != tail.getData()){
						run.next = run.next.next;
						return true;
					}
					else{
						tail = run;
						tail.next = null;
						return false;
					}
				}
				
				run = run.next;
			}
		}
		
		return false;
	}
	
	public boolean insertAfter(ListElement element, int data){
		
		boolean res = false;
		//Null list
		if (this.head == null && element == null){
			ListElement temp = new ListElement(data);
			head = temp;
			tail = this.head;
			res = true;
		}
		else
			//The element is at the tail
			if (element.getData() == tail.getData()){
				ListElement temp = new ListElement(data);
				tail.next = temp;
				tail = temp;
			}
			//The element is not at the tail
			else{
				ListElement run = head;
				while (run != null){
					System.out.println("Running...");
					if (run.getData() == element.getData()){
						//Found it
						System.out.println("Found it");
						ListElement temp = new ListElement(data);
						temp.next = run.next;
						run.next = temp;
						res = true;
					}
					else{
						//Didn't find it
					}
					run = run.next;
				}
				System.out.println("Stopped running");
			}
		return res;
	}
}
